"""发送请求模块"""

import asyncio
import json
from typing import Callable
from concurrent.futures import ThreadPoolExecutor

import aiohttp
from loguru import logger


class Wrapper(object):

    def __init__(self, tip: str, default_result=None, thread_count=3):
        self._tip = tip
        self._default_result = default_result
        self._pool = ThreadPoolExecutor(max_workers=thread_count)

    def __call__(self, func: Callable):
        def wrapper(*args, **kwargs):
            if self._default_result is None:
                self._pool.submit(self._run, func, *args, **kwargs)
            else:
                result = self._run(func, *args, **kwargs)
                return result

        return wrapper

    def _run(self, func: Callable, *args, **kwargs):
        result = None
        try:
            loop = asyncio.new_event_loop()
            result = loop.run_until_complete(func(*args, **kwargs))

        except:
            logger.exception(f'【request】{self._tip}失败')
            result = self._default_result

        finally:
            return result


class Request(object):

    @staticmethod
    @Wrapper('回调检测结果', default_result=None)
    async def _callback_result(message: dict, url: str):
        async with aiohttp.ClientSession() as session:
            logger.debug(f'【Request-callback_result】发送post请求,url:{url}')
            resp = await session.post(url, json=message)
            await resp.release()

    @classmethod
    def callback_result(cls, message: dict, *, url: str):
        cls._callback_result(message, url)
